package controllers

import "LoginTemplate/models"

type ConfigController struct {
	BaseController
}

type Config struct {
	ID            int    `json:"id"`
	PaymentMethod string `json:"payment_method"`
	IsDe          int    `json:"is_de"`
}

// 添加配置
func (u *ConfigController) InsertConfig() {
	var config Config
	err := u.ShouldBind(&config)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "insert into config ( payment_method ) values ( ? )"
	tx := models.DB.Debug().Exec(sql, config.PaymentMethod)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 修改配置
func (u *ConfigController) UpdateConfig() {
	var config Config
	err := u.ShouldBind(&config)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "update config set payment_method = ?,is_de = ? where id = ?"
	tx := models.DB.Debug().Exec(sql, config.PaymentMethod, config.IsDe, config.ID)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

type ConfigData struct {
	Code        int      `json:"code"`
	Msg         string   `json:"msg"`
	Data        []Config `json:"data"`
	Sum         int      `json:"sum"`         //总页数
	CurrentPage int      `json:"currentPage"` //当前页
	TotalNumber int      `json:"totalNumber"` //总条数
}

// 查询配置
func (u *ConfigController) SelectConfig() {
	var pictureList PictureList
	err := u.ShouldBind(&pictureList)
	var sum int
	var totalNumber int
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var shop []Config
	sql := "select * from config limit ? , ?"
	tx := models.DB.Debug().Raw(sql, (pictureList.Page-1)*pictureList.Size, pictureList.Size).Scan(&shop)
	sqlsum := "SELECT CEIL(COUNT(*) / ? ) FROM config"
	models.DB.Debug().Raw(sqlsum, pictureList.Size).Scan(&sum)
	sqlNumBer := "select count(*) from config"
	models.DB.Debug().Raw(sqlNumBer).Scan(&totalNumber)
	if tx.Error != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var picturedata ConfigData
	picturedata.Code = 200
	picturedata.Data = shop
	picturedata.Msg = "成功"
	picturedata.Sum = sum
	picturedata.CurrentPage = pictureList.Page
	picturedata.TotalNumber = totalNumber
	//return picturedata
	u.JsonMsg(200, map[string]interface{}{
		"list":  picturedata,
		"count": "",
	}, "success")
}

// 删除配置
func (u *ConfigController) DeleteCofig() {
	var config Config
	err := u.ShouldBind(&config)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "delete from config where id = ?"
	tx := models.DB.Debug().Exec(sql, config.ID)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}
